import PageHeaderWrapper from "@/components/PageHeaderWrapper";
import PageLoading from "@/components/PageLoading";
import { Card, Dropdown, Form, Icon, Input, Layout, Menu, Modal, Pagination, Spin, Table, Tree, message } from "antd";
import React, { Suspense } from "react";
import { formatMessage } from "umi-plugin-react/locale";
import styles from "./index.less";
import moment from "moment";
import { ButtonGroup, ImportModal } from "@/utils/CommonComponent";
import { formDictionaryDownload } from "@/services/formInteraction";
import UserUpdate from "./userUpdate";
import {
  selfBuiltList,
  selfBuiltListDelete,
  selfBuiltListEdit,
  selfBuiltPasswordReset,
  selfBuiltTree,
  selfBuiltTreeAdd,
  selfBuiltTreeDelete,
  selfBuiltTreeEdit,
} from "@/services/aigcUser";
import tableDataCheck from "@/utils/isBackPrevPage";

const { Header, Footer, Sider, Content } = Layout;

class SelfBuiltAccount extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      leftLoading: false,
      leftData: [],
      overlayVisible: false,
      currentNode: {},
      modalType: "",
      modalVisible: false,
      optNode: {},
      selectedKeys: [],
      expandedKeys: [],
      list: [],
      current: 1,
      size: 10,
      categoryId: "",
      name: "",
      loading: false,
      importVisible: false,
      importLoading: false,
    };
  }

  componentDidMount() {
    this.getLeftData("init");
  }

  getLeftData = (flag) => {
    const { expandedKeys, currentNode } = this.state;
    this.setState(
      {
        leftLoading: true,
      },
      async () => {
        const res = await selfBuiltTree();
        this.setState(
          {
            leftLoading: false,
            leftData: res ? res : [],
            expandedKeys: flag && flag == "init" ? (res && res[0] ? [res[0].id] : []) : expandedKeys,
            currentNode: flag && flag == "init" ? (res && res[0] ? { eventKey: res[0].id, info: res[0] } : { info: {} }) : currentNode,
          },
          () => {
            if (flag && flag == "init") {
              this.getTableData();
            }
          }
        );
      }
    );
  };

  openEditModal = (e) => {
    e.domEvent.persist();
    e.domEvent.stopPropagation();
    const { optNode } = this.state;
    optNode.isEdit = true;
    optNode.editName = optNode.name;
    this.setState({
      optNode,
    });
  };

  editName = async (values) => {
    const { optNode } = this.state;
    const name = optNode.editName;
    if (name == "" || name === optNode.name) {
      optNode.isEdit = false;
      this.setState({
        optNode: {},
      });
    } else {
      const res = await selfBuiltTreeEdit({ id: optNode.id, name });
      message.info(res.message);
      this.getLeftData();
      this.setState({
        optNode: {},
      });
    }
  };

  addName = (e, item) => {
    e.persist();
    e.stopPropagation();
    this.setState(
      {
        optNode: item,
      },
      async () => {
        const { expandedKeys } = this.state;
        const res = await selfBuiltTreeAdd({
          name: formatMessage({ id: "selfBuiltAccount.index.unnamedCategorySuffix" }) + this.generateRandom(),
          parentId: item.id,
        });
        message.info(res.message);
        this.getLeftData();
        if (expandedKeys.indexOf(item.id) == -1) {
          expandedKeys.push(item.id);
        }
        this.setState({
          optNode: {},
          expandedKeys,
        });
      }
    );
  };

  showMenu = (e, item) => {
    e.persist();
    e.stopPropagation();
    this.setState({
      optNode: item,
    });
  };

  onSelect = (selectedKeys, e) => {
    console.log(selectedKeys, e);
    this.setState(
      {
        currentNode: e.node.props,
        selectedKeys: [e.node.props.info.id],
      },
      () => {
        this.doSearch(1, 10);
      }
    );
  };

  onVisibleChange = (visible) => {
    if (!visible) {
      this.setState({
        optNode: { info: {} },
      });
    }
  };

  deleteConfirm = (e) => {
    e.domEvent.persist();
    e.domEvent.stopPropagation();
    Modal.confirm({
      title: formatMessage({ id: "selfBuiltAccount.index.confirmDeleteTitle" }),
      okText: formatMessage({ id: "common.ok" }),
      cancelText: formatMessage({ id: "common.cancel" }),
      okType: "danger",
      onOk: () => {
        this.doConfirm();
      },
    });
  };

  doConfirm = async () => {
    const { optNode } = this.state;
    const res = await selfBuiltTreeDelete({ categoryId: optNode.id });
    message.info(res.message);
    this.getLeftData("init");
    this.setState({
      optNode: {},
    });
  };

  onExpand = (expandedKeys) => {
    this.setState({
      expandedKeys,
    });
  };

  changeName = (e) => {
    e.persist();
    const { optNode } = this.state;
    optNode.editName = e.target.value;
    this.setState({
      optNode,
    });
  };

  doSearch = (current, size) => {
    this.setState(
      {
        current,
        size,
      },
      () => {
        this.getTableData();
      }
    );
  };

  getTableData = () => {
    this.setState(
      {
        loading: true,
      },
      async () => {
        const { current, size, currentNode, name } = this.state;
        const res = await selfBuiltList({
          current,
          size,
          categoryId: currentNode.info.id,
          name,
        });

        this.setState({
          loading: false,
          list: res.records,
          total: res.total,
        });
      }
    );
  };

  handleDownload = async () => {
    const res = await formDictionaryDownload();
  };

  handleUpload = (info) => {
    const that = this;
    this.setState(
      {
        importLoading: true,
      },
      () => {
        const file = info.file;
        if (file.status == "done" && file.response) {
          const response = file.response;
          if (response.code == 0) {
            console.log(response.data);
            that.handleCancel();
            that.getTableData();
          }
          message.info(response.message);
          that.setState({
            importLoading: false,
          });
        }
      }
    );
  };

  handleCancel = () => {
    this.setState({
      importLoading: false,
      importVisible: false,
    });
  };

  openUpdateModal = (id) => {
    const title = id ? formatMessage({ id: "selfBuiltAccount.userUpdate.form.editUser" }) : formatMessage({ id: "selfBuiltAccount.index.addUser" });
    this.UserUpdate.doInit(id, title);
  };

  resetConfirm = (id) => {
    const that = this;
    Modal.confirm({
      title: formatMessage({ id: "selfBuiltAccount.index.confirmResetPasswordTitle" }),
      okText: formatMessage({ id: "common.ok" }),
      cancelText: formatMessage({ id: "common.cancel" }),
      okType: "danger",
      onOk: () => {
        that.doReset(id);
      },
    });
  };

  doReset = async (id) => {
    const res = await selfBuiltPasswordReset({ id });
    message.info(res.data);
  };

  startOrStop = async (row) => {
    const res = await selfBuiltListEdit({ id: row.id, disabled: !row.disabled });
    message.info(res.message);
    this.getTableData();
  };

  removeItemConfirm = (id) => {
    Modal.confirm({
      title: formatMessage({ id: "selfBuiltAccount.index.confirmDeleteTitle" }),
      okText: "确定",
      cancelText: "取消",
      okType: "danger",
      onOk: () => {
        this.doItemConfirm(id);
      },
    });
  };

  doItemConfirm = async (id) => {
    const { list, current, size } = this.state;
    const res = await selfBuiltListDelete({ id });
    message.info(res.message);
    const newCurrent = tableDataCheck(list, current);
    this.doSearch(newCurrent, size);
  };

  generateRandom() {
    return Math.floor(Math.random() * 9000) + 1000;
  }

  render() {
    const {
      leftLoading,
      leftData,
      modalType,
      modalVisible,
      selectedKeys,
      optNode,
      currentNode,
      expandedKeys,
      name,
      current,
      size,
      list,
      loading,
      total,
      importVisible,
      importLoading,
    } = this.state;
    const {
      form: { getFieldDecorator },
    } = this.props;
    const menu = (
      <Menu>
        <Menu.Item key="1" onClick={(e) => this.openEditModal(e)}>
          <Icon type="form" style={{ fontSize: 14 }} />
          <span>{formatMessage({ id: "selfBuiltAccount.index.editName" })}</span>
        </Menu.Item>
        <Menu.Item key="5" onClick={(e) => this.deleteConfirm(e)}>
          <Icon type="delete" style={{ fontSize: 14 }} />
          <span>{formatMessage({ id: "selfBuiltAccount.index.delete" })}</span>
        </Menu.Item>
      </Menu>
    );
    const renderTreeTitle = (item) => (
      <div
        className={
          optNode.id == item.id
            ? currentNode.eventKey == item.id
              ? `${styles.treeNameBox} ${styles.treeNameOpt} ${styles.treeNameSelect}`
              : `${styles.treeNameBox} ${styles.treeNameOpt}`
            : currentNode.eventKey == item.id
            ? `${styles.treeNameBox} ${styles.treeNameSelect}`
            : `${styles.treeNameBox}`
        }
      >
        <div className={styles.treeName} title={item.name}>
          {optNode.id == item.id && optNode.isEdit ? (
            <Input
              placeholder={formatMessage({ id: "selfBuiltAccount.index.categoryNamePlaceholder" })}
              value={optNode.editName}
              onChange={(e) => this.changeName(e)}
              onBlur={(e) => this.editName(e)}
            />
          ) : (
            item.name
          )}
        </div>
        <div className={styles.moreOpt}>
          <div className={styles.plusIconBox} onClick={(e) => this.addName(e, item)}>
            <img src="../../../newUI/plus.png" className={styles.plusIcon} />
          </div>
          {item.parentId != 0 ? (
            <Dropdown overlay={menu} trigger={["click"]} onVisibleChange={this.onVisibleChange}>
              <div className={styles.optIconBox} onClick={(e) => this.showMenu(e, item)}>
                <img src="../../../newUI/opt.png" className={styles.optIcon} />
              </div>
            </Dropdown>
          ) : (
            ""
          )}
        </div>
      </div>
    );
    const renderTreeNode = (data) =>
      data.map((item) =>
        item.children && item.children.length > 0 ? (
          <Tree.TreeNode title={renderTreeTitle(item)} key={item.id} info={{ id: item.id, name: item.name }}>
            {renderTreeNode(item.children)}
          </Tree.TreeNode>
        ) : (
          <Tree.TreeNode title={renderTreeTitle(item)} key={item.id} info={{ id: item.id, name: item.name }} />
        )
      );
    const columns = [
      {
        title: formatMessage({ id: "selfBuiltAccount.index.userName" }),
        dataIndex: "nickName",
        width: 200,
      },
      {
        title: formatMessage({ id: "selfBuiltAccount.index.email" }),
        dataIndex: "email",
        width: 200,
      },
      {
        title: formatMessage({ id: "selfBuiltAccount.index.loginUsername" }),
        dataIndex: "userName",
        width: 120,
      },
			{
				title: formatMessage({ id: "selfBuiltAccount.index.mobilePhone" }),
				dataIndex: "mobilePhone",
				width: 120,
			},
      {
        title: formatMessage({ id: "selfBuiltAccount.index.role" }),
        dataIndex: "roleNameStr",
        width: 120,
      },
      {
        title: formatMessage({ id: "selfBuiltAccount.index.createTime" }),
        dataIndex: "createTime",
        key: "createTime",
        width: 150,
        render: (createTime) => {
          if (createTime) {
            return moment(createTime).format("YYYY-MM-DD hh:mm:ss");
          } else {
            return createTime;
          }
        },
      },
      {
        title: formatMessage({ id: "selfBuiltAccount.index.operation" }),
        width: 200,
        render: (text, row) => {
          return (
            <div>
              <ButtonGroup
                title={formatMessage({ id: "selfBuiltAccount.index.edit" })}
                group="edit-table"
                handleClick={() => this.openUpdateModal(row.id)}
              />
              <ButtonGroup
                title={formatMessage({ id: "selfBuiltAccount.index.resetPassword" })}
                group="reset-table"
                handleClick={() => this.resetConfirm(row.id)}
              />
              {row.disabled ? (
                <ButtonGroup
                  title={formatMessage({ id: "selfBuiltAccount.index.enable" })}
                  group="start-table"
                  handleClick={() => this.startOrStop(row)}
                />
              ) : (
                <ButtonGroup
                  title={formatMessage({ id: "selfBuiltAccount.index.disable" })}
                  group="stop-table"
                  handleClick={() => this.startOrStop(row)}
                />
              )}
              <ButtonGroup
                title={formatMessage({ id: "selfBuiltAccount.index.delete" })}
                group="delete-table"
                handleClick={() => this.removeItemConfirm(row.id)}
                style={{ marginRight: 0 }}
              />
            </div>
          );
        },
      },
    ];
    return (
      <Suspense fallback={<PageLoading />}>
        <PageHeaderWrapper>
          <Layout style={{ height: "100%" }} className={styles.accountCard}>
            <Sider
              theme="light"
              width={300}
              style={{ background: "#ffffff", borderRadius: "6px 0 0 6px", borderRight: "1px solid #E7E7E7", padding: 10 }}
            >
              <Spin spinning={leftLoading}>
                <Tree
                  showIcon={false}
                  defaultExpandAll
                  onSelect={this.onSelect}
                  selectedKeys={selectedKeys}
                  expandedKeys={expandedKeys}
                  onExpand={this.onExpand}
                >
                  {renderTreeNode(leftData)}
                </Tree>
              </Spin>
            </Sider>
            <Content style={{ background: "#ffffff", borderRadius: "0 6px 6px 0", padding: 22 }}>
              <div className={styles.tableTop}>
                <Input.Search
                  placeholder={formatMessage({ id: "selfBuiltAccount.index.inputLoginUsername" })}
                  value={name}
                  onChange={(e) => this.setState({ name: e.target.value })}
                  onSearch={() => this.doSearch(1, size)}
                  style={{ width: 200 }}
                />
                <div style={{ flexShrink: "0" }}>
                  <ButtonGroup
                    title={formatMessage({ id: "selfBuiltAccount.index.addUser" })}
                    group="add"
                    handleClick={() => this.openUpdateModal()}
                    style={{ marginRight: 0 }}
                  />
                </div>
              </div>
              <Table
                dataSource={list}
                loading={loading}
                rowKey="id"
                pagination={false}
                scroll={{ x: "auto", y: "calc(100vh - 300px)" }}
                columns={columns}
              />
              {parseInt(total) > 10 ? (
                <Pagination showQuickJumper total={total} current={current} onChange={this.doSearch} style={{ textAlign: "right", marginTop: 16 }} />
              ) : null}
            </Content>
          </Layout>

          <ImportModal
            attributeList={{
              title: formatMessage({ id: "selfBuiltAccount.index.import" }),
              visible: importVisible,
            }}
            handleCancel={this.handleCancel}
            handleDownload={this.handleDownload}
            importUrl="/cloud/form/dictionary/import"
            handleUpload={this.handleUpload}
            importLoading={importLoading}
          />
          <UserUpdate onRef={(ref) => (this.UserUpdate = ref)} currentNode={currentNode} doRefresh={() => this.doSearch(1, size)} />
        </PageHeaderWrapper>
      </Suspense>
    );
  }
}

export default Form.create()(SelfBuiltAccount);
